<!-- 新建销售类合同模板 -->
<template>
  <div class="index">
    <pageHeader :title="title" :bread-crumb="breadCrumb" :show-back="true">
      <template #buts>
        <a-button html-type="submit" type="primary" @click="save">{{
          form.template.id > 0 ? '保存' : '添加'
        }}</a-button>
        <a-button @click="cancel">取消</a-button>
      </template>
    </pageHeader>
    <!------------------------------------------>
    <div class="content">
      <div class="title">基础设置</div>
      <a-form
        auto-label-width
        ref="demandTemplateRef"
        layout="vertical"
        :model="form.template"
      >
        <a-form-item
          field="tempName"
          label="合同模板名称"
          validate-trigger="input"
          required
        >
          <a-input
            v-model="form.template.tempName"
            placeholder="请输入合同模板名称"
            message="此项必填"
          />
        </a-form-item>
        <a-form-item label="合同模板说明" validate-trigger="input">
          <a-textarea
            v-model="form.template.tempDes"
            placeholder="请输入说明描述该合同模板，100字符以内"
            :max-length="100"
            auto-size
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <a-form-item label="所属类型" required>
          <a-select
            v-model="filterListData"
            placeholder="请选择新建销售类合同模板类型"
            @change="filterList"
          >
            <a-option
              v-for="(item, index) in salesList.list"
              :value="item.id"
              :key="index"
              >{{ item.name }}</a-option
            >
          </a-select>
        </a-form-item>
        <!------------------------------------------>
        <div class="title">表单与流程</div>
        <a-form-item label="表单与打印" validate-trigger="blur" required>
          <!------------------------------------------>
          <a-input
            ref="inputRef"
            :model-value="formControlName"
            placeholder="请选择"
            message="此项必填"
            readonly
            @click="formClick"
          />
        </a-form-item>
        <!-- <a-form-item class="end-line" validate-trigger="blur">
          <a-checkbox value="1">上传并使用自定义打印模板</a-checkbox>
          <span class="set-print-model">点击设置</span>
        </a-form-item>
        <div class="title">规则与适用范围</div>
        <a-form-item label="适用范围" validate-trigger="blur">
          <a-radio-group
            direction="vertical"
            v-model="form.template.ctemp_scope"
          >
            <a-radio value="1">限定部门或人员适用</a-radio>
            <a-radio value="2">不限</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          class="end-line"
          label="合同金额可见"
          validate-trigger="blur"
        >
          <a-radio-group
            direction="vertical"
            v-model="form.template.ctemp_amount_viwe"
          >
            <a-radio value="1">仅当前录入人员和指定人员可见</a-radio>
            <a-radio value="2">不限</a-radio>
          </a-radio-group>
        </a-form-item> -->
        <!-- <a-form-item label="评审流程" validate-trigger="blur" required>
          <a-input
            ref="workFlowInputRef"
            :model-value="workFlowName"
            placeholder="请选择"
            message="此项必填!"
            readonly
            @click="workFlowClick"
          />
        </a-form-item> -->
      </a-form>
    </div>
    <!---------------------------------------------------------------------------------------------------->
    <!---------------------------------------------------------------------------------------------------->
    <!---------------------------------------------------------------------------------------------------->
    <!-- 图标选择弹框 -->
    <a-modal
      v-model:visible="iconModalVisible"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template #title> 图标列表 </template>
      <div>选择图标：</div>
    </a-modal>
    <!---------------------------------------------------------------------------------------------------->
    <!---------------------------------------------------------------------------------------------------->
    <!---------------------------------------------------------------------------------------------------->
    <!-- 表单与流程弹框设置 -->
    <a-modal
      v-model:visible="formModalVisible"
      class="form-modal"
      width="60%"
      :esc-to-close="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template #title>
        <h2>表单与打印</h2>
      </template>
      <div class="tips">不同合同模板类型下的表单无法共享</div>
      <a-button long type="outline" @click="formCreate">
        <template #icon> <icon-plus /> </template>新建表单并使用
      </a-button>
      <div class="meta">
        <div>选择已有表单使用</div>
        <a-input-search :style="{ width: '320px' }" placeholder="请输入名称" />
      </div>
      <div class="form-list-content">
        <a-empty v-if="formList.list.length == 0" />

        <a-radio-group
          v-model="contractCheckValue"
          direction="vertical"
          style="width: 100%"
        >
          <div v-for="item in formList.list" :key="item.id" class="form-list">
            <a-radio :value="item.id">
              <div class="form-name">{{ item.name }}</div>
              <div class="form-info">
                <span
                  >创建时间：{{
                    `${dayjs(item.createdAt).format('YYYY-MM-DD')}`
                  }}</span
                >
                <span>创建人：{{ item.UserName }}</span>
              </div>
            </a-radio>
            <a-space class="btn-group">
              <a-button type="text" @click="edit(item.id)">编辑</a-button>
              <!-- <a-button type="text" @click="copyFormProcess(item.id)"
                >复制</a-button -->

              <a-popconfirm
                content="确定删除吗?"
                @ok="deleteOrderDesignDelPrint(item.id)"
              >
                <a-button type="text">删除</a-button>
              </a-popconfirm>
            </a-space>
          </div>
        </a-radio-group>
      </div>
    </a-modal>
    <!---------------------------------------------------------------------------------------------------->
    <!---------------------------------------------------------------------------------------------------->
    <!---------------------------------------------------------------------------------------------------->
    <!-- 控件表单选择弹框 -->
    <formControlCreate
      ref="formControl"
      :data="data"
      @saveForm="saveForm"
    ></formControlCreate>

    <workflow
      ref="workFlowRef"
      :workFlowList="workFlowList"
      :flowId="form.template.flowId"
      @update:workFlowList="choiseFlow"
      @createFlow="createFlow"
    >
    </workflow>
    <FlowSet
      ref="flowSetRef"
      :showTemplate="false"
      :conditionForm="conditionForm"
      :data="flowData.list"
      @update:data="saveData"
    ></FlowSet>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, nextTick, onMounted, inject, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import uniqueid from 'lodash.uniqueid';
  import dayjs from 'dayjs';
  import { GetContractTypeSetting } from '@/api/contract-management/base-setting/type-contract/index';

  import {
    GetContractDesignList,
    GetContractDesign,
    PostContractDesign,
    PutContractDesign,
    GetContractTemplate,
    GetByIdContractTemplate,
    PostContractTemplate,
    CopyContractTemplate,
    PutContractTemplate,
    DeleteContractDesign,
  } from '@/api/contract-management/base-setting/template-contract/index';
  import { postBasisFlowSearch } from '@/api/home/System settings/basis-flow';
  import {
    postBasisFlow,
    getBasisFlow,
    putBasisFlow,
  } from '@/api/order-management/client-management/order';
  import type { FlowDataType, FlowItem } from '@/types/flow';
  import workflow from '../flow/index.vue';
  import FlowSet from '../flow/flow-set.vue';

  const active = ref(false);
  const router = useRouter();
  const inputRef = ref();
  const breadCrumb: string[] = [
    '合同管理',
    '基础设置',
    '合同模板',
    '新建采购类合同模板',
  ];
  const title = ref('新建采购类合同模板');
  const form = reactive({
    template: {
      id: undefined,
      tempName: '', // 合同模板名称
      tempDes: '', // 合同模板类型说明
      // 所属类型
      ctemp_typeid: undefined, // 合同所属类型id
      ctempTypeName: '', // 合同所属类型
      logo: '',
      state: 2,
      ctemp_typeid_parent: 2, // 1销售 2采购
      ctemp_design_id: 0, // 合同表单id
      // 表单与流程
      contractDesignName: '', // 表单与打印
      is_upload_print: undefined, // 上传并使用自定义打印模板
      // 规则与适用范围
      ctemp_scope: undefined, // 使用范围人（人员id组）1.限定部门或人员适用 2.不限
      ctemp_amount_viwe: undefined, // 合同金额可见人（人员id组）.限定部门或人员适用 2.不限
      // 审批流程
      flowId: undefined,
      ctemp_approve_id: undefined, // 审批id
      ctemp_approve_type: undefined, // 审批类型
      ctemp_approve_check: undefined, // 选择审批
    },
  });

  // *所属类型 选择下拉框
  const salesList = reactive<any>({
    list: [],
  });

  // onMounted(async () => {

  //   // console.log('router', router.currentRoute.value.query.id);
  //   // let demandTemplateId = Number(router.currentRoute.value.query.id);
  //   // if (demandTemplateId > 0) {
  //   //   getDemandTemplate(demandTemplateId);
  //   // }
  //   // title.value = demandTemplateId > 0 ? '编辑需求模板' : '新建需求模板';
  // });

  const radioValue = ref(1);
  const iconModalVisible = ref(false);
  // 切换图标
  const iconClick = () => {
    iconModalVisible.value = true;
  };

  const handleCancel = () => {
    iconModalVisible.value = false;
  };
  const formModalVisible = ref(false);
  interface FormList {
    data: {
      list: {
        id: number;
        ctemp_typeid_parent: number;
        ctemp_typeid: number;
        name: string;
        user_id: number;
        UserName: string;
        checked: number;
        Form: any;
        Print: any;
        createdAt?: string;
        updateAt?: string;
        deletedAt?: string;
      };
    };
  }
  const formList = reactive<any>({
    list: [],
  });
  // 表单与打印配置 列表
  const getFormList = async () => {
    let params = { ctemp_typeid: 1 }; // 默认1 ，1销售 2采购
    formList.list = [];
    const res = await GetContractDesignList();
    formList.list = res.data;
  };

  const contractCheckValue = ref(0);
  const formClick = () => {
    // getFormList(); // 获取销售类合同模板列表
    contractCheckValue.value = form.template.ctemp_design_id;
    formModalVisible.value = true;
  };
  // const rowSelection = {
  //   type: 'radio',
  // };

  const formShow = ref(false);
  const formControl = ref();
  interface DataTYpe {
    id?: number;
    ctemp_typeid_parent: number;
    name: string;
    form: any[];
    print: any[];
  }

  //控件表单数据
  let data = reactive<DataTYpe>({
    id: undefined,
    ctemp_typeid_parent: 2, // 1销售 2采购
    name: '新建表单',
    form: [],
    print: [],
  });
  const reset = () => {
    data.id = undefined;
    data.ctemp_typeid_parent = 2; // 1销售 2采购
    data.name = '新建表单';
    data.form = [];
    data.print = [];
  };

  const mustFormData = [
    {
      show: 1,
      componentType: 'NUMBER-UNIVERSAL',
      code: 'NUMBER-UNIVERSAL',
      props: { placeholder: '请输入合同名称' },
      name: '合同编号',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'number',
    },
    {
      show: 1,
      componentType: 'TEXT',
      code: 'TEXT',
      props: { placeholder: '请输入合同名称' },
      name: '合同名称',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'name',
    },
    {
      show: 1,
      componentType: 'SUOOLIER-NAME',
      code: 'SUOOLIER-NAME',
      props: { placeholder: '请输入客户名称' },
      name: '供应商名称',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'supplierId',
    },
    {
      show: 1,
      componentType: 'CONTACT_NAME',
      code: 'CONTACT_NAME',
      props: { placeholder: '选择客户自动获取联系人' },
      name: '联系人',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'contactName',
    },
    {
      show: 1,
      componentType: 'CONTACT-NUMBER',
      code: 'CONTACT-NUMBER',
      props: { placeholder: '选择供应商自动获取联系电话' },
      name: '联系电话',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'clientPhone',
    },
    {
      show: 1,
      componentType: 'CONTACT-ADDRESS',
      code: 'CONTACT-ADDRESS',
      props: { placeholder: '选择供应商自动获取联系地址' },
      name: '联系地址',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'address',
    },
    // {
    //   show: 1,
    //   componentType: 'COMPANY',
    //   code: 'COMPANY',
    //   props: { placeholder: '请选择我方签约主体' },
    //   name: '我方签约主体',
    //   required: 1,
    //   span: 24,
    //   uuid: uniqueid(''),
    //   isMust: 1,
    //   isProcessConditions: 1,
    //   fieldName: 'company',
    // },
    {
      show: 1,
      componentType: 'COMPANY',
      code: 'COMPANY',
      props: { placeholder: '请选择我方签约人' },
      name: '我方签约人',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'ourSignUser',
    },
    {
      show: 1,
      componentType: 'DEPARTMENT',
      code: 'DEPARTMENT',
      props: { placeholder: '请选择部门' },
      name: '部门',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'department',
    },
    {
      show: 1,
      componentType: 'POST',
      code: 'POST',
      props: { placeholder: '请选择职位' },
      name: '职位',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'post',
    },
    {
      show: 1,
      componentType: 'BUSINESS_COPYING',
      code: 'BUSINESS_COPYING',
      props: { placeholder: '请选择业务跟单人' },
      name: '业务跟单',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'businessCopying',
    },
    {
      show: 1,
      componentType: 'AGENCY_DATE',
      code: 'AGENCY_DATE',
      props: { placeholder: '请选择签约日期' },
      name: '签约日期',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'orderTime',
    },
    {
      show: 1,
      componentType: 'END_DATE',
      code: 'END_DATE',
      props: { placeholder: '请选择结束日期' },
      name: '结束日期',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'endTime',
    },
    {
      show: 1,
      componentType: 'CONTRACT_CONTENT',
      code: 'CONTRACT_CONTENT',
      props: { placeholder: '请填写合同内容' },
      name: '合同内容',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'contractContent',
    },
    {
      show: 1,
      componentType: 'CONTRACT_PAYMENT',
      code: 'CONTRACT_PAYMENT',
      props: { placeholder: '请填写付款方式' },
      name: '付款方式',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'contractPayment',
    },
    {
      show: 1,
      componentType: 'CONTRACT_TOTAL',
      code: 'CONTRACT_TOTAL',
      props: { placeholder: '请输入合同总金额' },
      name: '合同总金额',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'ctotalPrice',
    },

    {
      show: 1,
      componentType: 'PAYMENT_DETAILS',
      code: 'PAYMENT_DETAILS',
      props: {
        columns: [
          {
            title: '付款期数',
            dataIndex: 'stages',
            slotName: 'stages',
          },
          {
            title: '付款条件',
            dataIndex: 'condition',
            slotName: 'condition',
          },
          {
            title: '付款金额',
            dataIndex: 'amount',
            slotName: 'amount',
          },
          {
            title: '付款比例',
            dataIndex: 'rate',
            slotName: 'rate',
          },
          {
            title: '付款类别',
            dataIndex: 'type',
            slotName: 'type',
          },
          {
            title: '支付方式',
            dataIndex: 'method',
            slotName: 'method',
          },
          {
            title: '备注',
            dataIndex: 'remark',
            slotName: 'remark',
          },
          {
            title: '操作',
            dataIndex: 'optional',
            slotName: 'optional',
          },
        ],
        data: [
          {
            stages: '',
            condition: '',
            amount: '',
            rate: '',
            type: '',
            method: '',
            remark: '',
          },
        ],
      },
      name: '付款明细',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'paymentDetails',
    },
    {
      show: 1,
      componentType: 'RECEIVING_ACCOUNT',
      code: 'RECEIVING_ACCOUNT',
      props: { placeholder: '请选择收款账户' },
      name: '收款账户',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'receivingAccount',
    },
    {
      show: 1,
      componentType: 'INVOICE_TYPE',
      code: 'INVOICE_TYPE',
      props: { placeholder: '请选择发票类型' },
      name: '发票类型',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'invoiceId',
    },
    {
      show: 1,
      componentType: 'INVOICE_RATE',
      code: 'INVOICE_RATE',
      props: { placeholder: '请选择发票税率' },
      name: '发票税率',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'invoiceRate',
    },
    {
      show: 1,
      componentType: 'COMPANY_TITLE',
      code: 'COMPANY_TITLE',
      props: { placeholder: '请输入单位抬头' },
      name: '单位抬头',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'companyTitle',
    },
    {
      show: 1,
      componentType: 'TAXPAYER_IDENTIFICATION_NUMBER',
      code: 'TAXPAYER_IDENTIFICATION_NUMBER',
      props: { placeholder: '请输入纳税人识别号' },
      name: '纳税人识别号',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'taxpayerIdentificationNumber',
    },
    {
      show: 1,
      componentType: 'ACCOUNT_BANK',
      code: 'ACCOUNT_BANK',
      props: { placeholder: '请选择开户行' },
      name: '开户行',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'accountBank',
    },
    {
      show: 1,
      componentType: 'UNIT_ADDRESS',
      code: 'UNIT_ADDRESS',
      props: { placeholder: '单位地址' },
      name: '单位地址',
      required: 1,
      span: 12,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'unitAddress',
    },
    {
      show: 1,
      componentType: 'INVOICE_REMARK',
      code: 'INVOICE_REMARK',
      props: { placeholder: '请输入备注信息' },
      name: '备注',
      required: 1,
      span: 24,
      uuid: uniqueid(''),
      isMust: 1,
      isProcessConditions: 1,
      fieldName: 'invoiceRemark',
    },
  ];
  // 新建需求表单
  const formCreate = () => {
    reset();
    data.form = mustFormData;
    formControl.value.fullScreen();
    // nextTick(() => {
    //   reset();
    // });
  };

  const demandCheckValue = ref(0);

  // 父组件获取子组件生成的表单id
  const getNewFormId = (id: number = 0) => {
    getFormList(); // 控件表单保存，发一次请求
    // 根据id获取对应名称
  };
  // 删除表单与打印配置
  const deleteOrderDesignDelPrint = async (id: number) => {
    await DeleteContractDesign(id);
    //删除此项，过滤
    formList.list = formList.list.filter((val) => val.id !== id);
    Message.success('删除成功');
  };

  const edit = async (id: number) => {
    const res = await GetContractDesign({ id });
    data.form = res.form;
    data.id = res.id;
    data.ctemp_typeid_parent = res.ctemp_typeid_parent;
    data.name = res.name;
    formControl.value.fullScreen();
  };

  const filterListData = ref();
  const filterList = async (val) => {
    filterListData.value = val;
    const resType = await GetContractTypeSetting();
    const res = await GetContractDesignList();
    formList.list = res.data.filter(({ ctemp_typeid }) =>
      resType.contractType.some(
        ({ id }) => id === ctemp_typeid && ctemp_typeid === val
      )
    );
  };

  const demandTemplateRef = ref();
  // 保存按钮,判断是否有id，没有是添加需求模板，有是修改
  const save = () => {
    // 表单规则验证
    demandTemplateRef.value.validate((res: unknown) => {
      if (res === undefined) {
        if (form.template.id === undefined) {
          const {
            tempName,
            tempDes,
            ctemp_typeid_parent,
            is_upload_print,
            ctemp_scope,
            ctemp_amount_viwe,
            ctemp_design_id,
          } = form.template;
          PostContractTemplate({
            createUserId: 1,
            tempName,
            tempDes,
            ctemp_typeid_parent,
            ctemp_typeid: filterListData.value,
            ctemp_status: 2,
            ctemp_scope: Number(ctemp_scope),
            ctemp_amount_viwe: Number(ctemp_amount_viwe),
            ctemp_design_id,
          }).then((res) => {
            console.log(res);
          });
        } else {
          PutContractTemplate(form.template).then((res) => {
            console.log(res);
          });
        }
        // 添加或编辑都需要判断一下此份模板状态是否是开启状态
        // if (form.template.state === 1) {
        //   // 应该查询状态开启的模板关闭，没有此接口，则查询全部模板
        //   GetContractTemplate({ ctemp_typeid: 1 }).then((res) => {
        //     let template = res.filter((item: any) => {
        //       return item.state === 1;
        //     });
        //     template[0].state = 2;
        //     // 调用修改接口
        //     PutContractTemplate(template[0]).then((updateRes) => {
        //       // 状态修改后
        //       if (form.template.id > 0) {
        //         console.log('form.template', form.template);
        //         // 编辑
        //         PutContractTemplate(form.template).then((res) => {
        //           Message.success('保存成功');
        //           console.log('编辑搜索', res);
        //         });
        //       } else {
        //         // 添加
        //         PostContractTemplate(form.template).then((item) => {
        //           console.log('添加', item);
        //           Message.success('添加成功');
        //         });
        //       }
        //     });
        //   });
        // } else {
        //   console.log('');
        //   if (form.template.id > 0) {
        //     console.log('form.template', form.template);
        //     // 编辑
        //     PutContractTemplate(form.template).then((res) => {
        //       console.log('编辑', res);
        //       Message.success('保存成功');
        //     });
        //   } else {
        //     // 添加
        //     PostContractTemplate(form.template).then((item) => {
        //       console.log('添加', item);
        //       Message.success('添加成功');
        //     });
        //   }
        // }
        router.back();
      }
    });
    // emit('codeSettingSave', Currlist.value)
  };

  // 取消按钮
  const cancel = () => {
    router.back();
  };

  //  根据控件表单id，获取对应的名称
  const formControlName = ref(); // 表单控件名称
  const conditionForm = ref([]);
  const getContractFromNameById = async (id: number) => {
    const res = await GetContractDesign({ id });
    conditionForm.value = res.form;
    form.template.ctemp_design_id = res.id;
    formControlName.value = res.name;
  };

  const getDemandTemplate = async (id: number) => {
    let params = {
      id,
    };
    const res = await GetByIdContractTemplate(params);
    form.template = res;
    filterListData.value = form.template.ctemp_typeid;
    filterList(filterListData.value);
    getContractFromNameById(form.template.ctemp_design_id);
  };

  const workFlowName = ref('');
  // 选中流程改变，获取对应审批名称
  const choiseFlow = async (id: number) => {
    form.template.flowId = id;
    let res = await getBasisFlow({ id });
    workFlowName.value = res.name;
  };

  // 选择控件表单
  const handleOk = () => {
    iconModalVisible.value = false;
    form.template.ctemp_design_id = contractCheckValue.value;
    getContractFromNameById(contractCheckValue.value);
    // console.log(form);
  };
  // 获取一份需求模板信息

  onMounted(async () => {
    const res = await GetContractTypeSetting();
    salesList.list = res.contractType;
    let contractTemplateId = Number(router.currentRoute.value.query.id);
    if (contractTemplateId > 0) {
      getDemandTemplate(contractTemplateId);
    }
    title.value =
      contractTemplateId > 0 ? '新建采购类合同模板' : '新建采购类合同模板';
  });
  // 监听控件表单id，获取对应的名称
  // watch(
  //   () => form.template.ctemp_design_id,
  //   (val) => {
  //     GetContractDesign({ id: val }).then((res) => {
  //       formControlName.value = res.name;
  //     });
  //   },
  //   { deep: true }
  // );

  // const filterContractDesignList = async () => {
  //   const { contractFrom } = await GetContractTypeSetting();
  //   const ids = new Set(contractFrom.map(({ id }) => id));
  //   const { data: list } = await GetContractDesignList();
  //   return list.filter(({ ctemp_typeid: id }) => ids.has(id));
  // };
  // formList.list = await filterContractDesignList();

  const saveForm = async (formData) => {
    // if (formData.id === undefined) {
    //   await PostContractDesign({
    //     name: formData.name,
    //     ctemp_typeid_parent: formData.ctemp_typeid_parent,
    //     ctemp_typeid: filterListData.value,
    //     checked: 2,
    //     form: formData.form,
    //     Print: formData.print,
    //   });
    // } else {
    //   await PutContractDesign({
    //     id: formData.id,
    //     name: formData.name,
    //     ctemp_typeid_parent: formData.ctemp_typeid_parent,
    //     ctemp_typeid: filterListData.value,
    //     checked: 2,
    //     form: formData.form,
    //     Print: formData.print,
    //   });
    // }
    const { id, name, ctemp_typeid_parent, form, Print } = formData;
    const data = {
      name,
      ctemp_typeid_parent,
      ctemp_typeid: filterListData.value,
      checked: 2,
      form,
      Print,
    };
    if (id === undefined) {
      await PostContractDesign(data);
      filterList(filterListData.value);
    } else {
      await PutContractDesign({ ...data, id });
      filterList(filterListData.value);
    }
  };

  const workFlowInputRef = ref();
  const workFlowRef = ref();

  const flowSetRef = ref();
  const flowParams = reactive({
    pageIndex: 0,
    pageSize: 999,
    type: 1,
  });
  const workFlowList = ref([]);
  const getFlowList = async () => {
    let res = await postBasisFlowSearch(flowParams);
    workFlowList.value = res.Data;
  };
  const workFlowClick = async () => {
    workFlowRef.value.workFlowVisible = true;
    getFlowList();
  };
  let flowData = reactive<FlowDataType>({
    list: {
      type: 1,
      templateId: 0,
      name: '',
      userStaffId: 0,
      userStaffName: '',
      description: '',
      nodeConfig: {
        type: 0,
        name: '发起人',
        sort: 0,
        auditType: 0,
        approverType: 0,
        approverTypeId: 0,
        nodeUserList: [],
        approverIsEmpty: 0,
        conditionNodes: [],
        childNode: null,
      },
      status: 0,
      reCommit: 1,
      updatedUserStaffId: 0,
      updatedUserStaffName: '',
    },
  });
  const resetFlowData = () => {
    flowData.list = {
      type: 1,
      templateId: 0,
      name: '',
      userStaffId: 0,
      userStaffName: '',
      description: '',
      nodeConfig: {
        type: 0,
        name: '发起人',
        sort: 0,
        auditType: 0,
        approverType: 0,
        approverTypeId: 0,
        nodeUserList: [],
        approverIsEmpty: 0,
        conditionNodes: [],
        childNode: null,
      },
      status: 0,
      reCommit: 1,
      updatedUserStaffId: 0,
      updatedUserStaffName: '',
    };
  };
  // 有id编辑，无id添加
  const createFlow = async (id?: number) => {
    if (id && id > 0) {
      let res = await getBasisFlow({ id });
      flowData.list = res;
    } else {
      resetFlowData();
    }
    flowSetRef.value.fullScreen();
  };
  const editFlow = async (id: number) => {
    let res = await getBasisFlow({ id });
    flowData.list = res;
  };
  const saveData = async (data: FlowItem) => {
    let res;
    res = data.id ? await putBasisFlow(data) : await postBasisFlow(data);
    Message.success(data.id ? '保存成功' : '添加成功');
    getFlowList();
  };
</script>

<style scoped lang="less">
  .index {
    display: flex;
    flex-direction: column;
    height: 100%;
    .content {
      // height: 400px;
      flex: 1;
      overflow-y: auto;
      margin: 16px;
      padding: 16px;
      border: 1px solid #eee;
      box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.3);
      border-radius: 5px;

      .title {
        font-size: 16px;
        margin-bottom: 10px;
      }

      .end-line {
        padding-bottom: 16px;
        border-bottom: 15px solid #eee;
      }

      .set-print-model {
        margin-left: 16px;
        cursor: pointer;
        color: #409eff;
      }

      .line-box {
        display: flex;
      }
    }
  }

  .form-modal {
    display: flex;
    flex-direction: column;
    height: 100%;

    .tips {
      border-radius: 5px;
      background: rgba(230, 247, 255, 1);
      padding: 5px 10px;
      margin-bottom: 16px;
      font-size: 16px;
    }

    .meta {
      display: flex;
      justify-content: space-between;
      margin: 16px 0;
      font-size: 16px;
    }

    .form-list-content {
      flex: 1;
      overflow: auto;

      .form-list {
        border-bottom: 1px solid #eee;
        padding-bottom: 16px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;

        .form-name {
          font-size: 16px;
        }

        .form-info {
          font-size: 12px;
          color: #666;

          span {
            margin-right: 16px;
          }
        }
      }
    }
  }
</style>
